<template>
        <div class="dargcon"
         ref="dargRef"
        @mousedown="(e)=>onHandleDown(e)"  
        >
          <!-- 元素 拖拽缩放 -->
             <div class="dargs"  
             v-for="item in Object.keys(objs)"
             :key="item" 
             :dataId="objs[item].uid"
             :style="{transform:`translate(${objs[item].x}px,${objs[item].y}px)`}"
             >
               asd  x:{{objs[item].x}} y:{{objs[item].x}}
             </div>   
        </div>
</template>
<script lang="ts" setup>
import {reactive, ref} from 'vue';
interface ItemType {
            x:number,
            y:number,
            w:number,
            h:number,
            uid:String
}
const limits = 4;
const dargRef = ref<HTMLElement>(); 
const objs = ref<{
       [key:string]:ItemType
}>({
      'xxx111':{
            x:0,
            y:0,
            w:100,
            h:100,
            uid:'xxx111'
      }
})
const ikey = ref(false);
const posi = reactive({
      x:0,
      y:0
})
const n_posi = reactive({
      x:0,
      y:0
})
const onHandleLeave = ()=>{
     ikey.value=false;
}
document.addEventListener('mousemove',(e)=>onHandleMove(e))
document.addEventListener('mouseup',onHandleLeave)
// 鼠标移动
const onHandleMove = (e)=>{
     e.preventDefault();
     let doma = e.target;
     let ids = doma.getAttribute("dataid");
      
      if(ikey.value){   
          // 原来的位置+偏移量==新位置
          let dargRefs = dargRef.value?.getBoundingClientRect() as unknown as {left:number,width:number,height:number,top:number};
          // 临界点判断
          // 右边
          objs.value[ids].x = objs.value[ids]?.x + (e.pageX-posi?.x); 
          objs.value[ids].y = objs.value[ids]?.y + (e.pageY-posi?.y); 
        
          // x
          if(objs.value[ids].x < 0){
               objs.value[ids].x = 0;
          }else if((objs.value[ids].x + objs.value[ids].w) > dargRefs?.width){
               objs.value[ids].x = (dargRefs?.width) - objs.value[ids]?.w;
          }
          // y
          if(objs.value[ids].y < 0 ){
               objs.value[ids].y = 0;
          }else if((objs.value[ids].y + objs.value[ids].h) > dargRefs?.height){
               objs.value[ids].y = (dargRefs?.height) - objs.value[ids].h;
          }
          posi.x = e.pageX;
          posi.y = e.pageY; 
     }      
      
}
// 鼠标按下
const onHandleDown = (e)=>{
       ikey.value=true;  
       posi.x = e.pageX;
       posi.y = e.pageY;   
}

</script>
<style  scoped>


.dargcon{
      background-color: aliceblue;
      width: 300px;
      height: 300px;
      margin-left: 10px;
      margin-top: 20px;
}
.dargs{
      width: 100px;
      height: 100px;
      cursor: pointer;
      border: 1px solid #475569;
      box-sizing: border-box;
      /* transform: ; */
}
</style>